const Service = require('egg').Service;
class TokenService extends Service {
    async updateToken(token, time) {
        const row = {
            id: 1,
            access_token: token,
            time: time, // any other fields u want to update
        };
        const result = await this.app.mysql.update('token', row);
        return result.affectedRows == 1;
    }
    async getHttpToken() {
        const {
            ctx
        } = this;
        const result = await ctx.curl('https://open.welink.huaweicloud.com/api/auth/v2/tickets', {
            // 必须指定 method
            method: 'POST',
            // 通过 contentType 告诉 HttpClient 以 JSON 格式发送
            contentType: 'json',
            data: {
                "client_id": "20200211180239998884656",
                "client_secret": "a9e3c46a-d778-45d8-9cd5-0cd9d58ececd",
            },
            // 明确告诉 HttpClient 以 JSON 格式处理返回的响应 body
            dataType: 'json',

        });
        let now = new Date().getTime();
        let time = new Date().setTime(now + result.data.expires_in * 1000);
        const update = await this.updateToken(result.data.access_token, time);
        return update ? result.data.access_token : null;
    }
    async getToken() {
        let isToken = await this.checkToken();
        if (isToken) {
            return this.getSqlToken()
        } else {
            let newToken = await this.getHttpToken();
            return newToken == null ? null : newToken;
        }
    }

    async checkToken() {
        let time = await this.getSqlTime();
        let now = new Date().getTime();
        return now < time;
    }
    async getSqlToken() {
        const token = await this.app.mysql.get('token', {
            id: 1
        });
        let {
            access_token
        } = token;
        return access_token;
    }
    async getSqlTime() {
        const token = await this.app.mysql.get('token', {
            id: 1
        });
        let {
            time
        } = token;
        return time;
    }


}
module.exports = TokenService;